//
//  LoanResultViewController.m
//  Rong360
//
//  Created by tianliwei on 9/2/14.
//  Copyright (c) 2014 tianliwei. All rights reserved.
//

#import "LoanResultViewController.h"
#import "LoanHistoryViewController.h"
#import "LoanResultCell.h"
#import "LoanResultExtraCell.h"
#import "WebViewController.h"
@interface LoanResultViewController ()
@property (nonatomic, strong) UISegmentedControl *segmentedControl;
@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, strong) NSArray *unitTitles;
@property (nonatomic, strong) NSArray *results;
@property (nonatomic, strong) NSArray *lastResults;
@end

static NSString *CellIdentifier = @"Cell";
static NSString *ExtraCellIdentifier = @"ExtraCell";
@implementation LoanResultViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithLoanCal:(LoanCalculator *)loanCal{
    self = [super init];
    if (self) {
        self.loanCal = loanCal;
    }
    return self;
}

- (void)initTableFooterView{
    UIView *tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 175)];
    UILabel *label = [UILabel labelWithFrame:CGRectMake(15, 5, 300, 15) title:@"以上结果仅供参考，请以当地实际情况为准" fontColor:[UIColor lightGrayColor] fontSize:10];
    UIButton *ajTactics = [UIButton buttonWithType:UIButtonTypeCustom];
    [ajTactics setTag:0];
    [ajTactics setFrame:CGRectMake(15, 35, 290, 35)];
    [ajTactics setTitle:@"按揭贷款办理攻略" forState:UIControlStateNormal];
    [ajTactics.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [ajTactics setTitleEdgeInsets:UIEdgeInsetsMake(0, 6, 0, 0)];
    [ajTactics setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [ajTactics setBackgroundImage:[UIImage imageNamed:@"btn_grey_normal"] forState:UIControlStateNormal];
    [ajTactics setBackgroundImage:[UIImage imageNamed:@"btn_grey_focus"] forState:UIControlStateHighlighted];
    [ajTactics setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [ajTactics addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *gjjTactics = [UIButton buttonWithType:UIButtonTypeCustom];
    [gjjTactics setTag:4];
    [gjjTactics setFrame:CGRectMake(15, 80, 290, 35)];
    [gjjTactics setTitle:@"公积金贷款办理攻略" forState:UIControlStateNormal];
    [gjjTactics setTitleEdgeInsets:UIEdgeInsetsMake(0, 6, 0, 0)];
    [gjjTactics.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [gjjTactics setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [gjjTactics setBackgroundImage:[UIImage imageNamed:@"btn_grey_normal"] forState:UIControlStateNormal];
    [gjjTactics setBackgroundImage:[UIImage imageNamed:@"btn_grey_focus"] forState:UIControlStateHighlighted];
    [gjjTactics setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [gjjTactics addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *reCal = [UIButton buttonWithTag:1 frame:CGRectMake(15, 135, 135, 35) normalImage:[UIImage imageNamed:@"btn_qd_normal"] highlightedImage:[UIImage imageNamed:@"btn_qd_focus"] target:self action:@selector(buttonClicked:)];
    [reCal setTitle:@"重新计算" forState:UIControlStateNormal];
    [reCal.titleLabel setFont:[UIFont systemFontOfSize:15]];
    UIButton *sendResult = [UIButton buttonWithTag:2 frame:CGRectMake(170, 135, 135, 35) normalImage:[UIImage imageNamed:@"btn_tg_normal"] highlightedImage:[UIImage imageNamed:@"btn_tg_focus"] target:self action:@selector(buttonClicked:)];
    [sendResult setTitle:@"发送结果" forState:UIControlStateNormal];
    [sendResult.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [tableFooterView addSubview:label];
    [tableFooterView addSubview:ajTactics];
    [tableFooterView addSubview:gjjTactics];
    [tableFooterView addSubview:reCal];
    [tableFooterView addSubview:sendResult];
    self.tableView.tableFooterView = tableFooterView;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    //    self.stack = [NSMutableArray array];
    self.view.backgroundColor = [UIColor whiteColor];
    [self initSegmentControl];
    self.title = @"计算结果";
    self.titles = @[@"月供：",@"总利息：",@"本息合计：",@"贷款金额：",@"贷款期限："];
    self.unitTitles = @[@"元",@"元",@"元",@"万",@"年"];
    NSInteger rowHeight = 54;
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(IOS7_OR_LATER?0:-10, 50, UI_SCREEN_WIDTH, UI_NAVIFRAME_HEIGHT-50)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.rowHeight = rowHeight;
    self.tableView.scrollEnabled = YES;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"LoanResultCell" bundle:nil] forCellReuseIdentifier:CellIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:@"LoanResultExtraCell" bundle:nil] forCellReuseIdentifier:ExtraCellIdentifier];
    [self initTableFooterView];
    [self.view addSubview:self.tableView];
    self.loanStyle = Loan_bx;
    if (self.loanStyle == Loan_bx) {
        self.results = self.loanCal.result_bx;
    }else if (self.loanStyle == Loan_bj){
        self.results = self.loanCal.result_bj;
    }
    
    NSString *test = [[NSUserDefaults standardUserDefaults]objectForKey:@"cmonth_bx"];
    if (test) {
        self.lastResults = [self getLastDataWithType:self.loanStyle];
    }
    
    UIButton *historyButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [historyButton setBackgroundColor:[UIColor clearColor]];
    [historyButton setTitle:@"历史" forState:UIControlStateNormal];
    [historyButton addTarget:self action:@selector(history) forControlEvents:UIControlEventTouchUpInside];
    historyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    historyButton.frame = CGRectMake(0.0f, 0.0f, 40.0f, 25.0f);
    UIBarButtonItem *historyButtonItem = [[UIBarButtonItem alloc] initWithCustomView:historyButton];
    self.navigationItem.rightBarButtonItem = historyButtonItem;
    
}

- (void)history{
    self.hidesBottomBarWhenPushed = YES;
    LoanHistoryViewController *loanHistory = [[LoanHistoryViewController alloc]init];
    loanHistory.loanType = self.loanStyle;
    [self.navigationController pushViewController:loanHistory animated:YES];
}


- (void)buttonClicked:(UIButton *)sender{
    switch (sender.tag) {
        case 0:{
            self.hidesBottomBarWhenPushed = YES;
            WebViewController *webVC = [[WebViewController alloc]initWithUrl:SDBL title:@"商贷办理" desc:SDBLDesc];
            webVC.type = HTML5ShareUrl;
            [self.navigationController pushViewController:webVC animated:YES];
            break;
        }
        case 1:{
            [self.navigationController popViewControllerAnimated:YES];
            break;
        }
        case 2:{
            NSString *shareText = [NSString stringWithFormat:@"我在#融360买房助手#算中测得我按揭贷款%@万，公积金贷款%@万，还%@年，每月要还%@元。这个应用真的很强大，用了之后，基本不怕被中介忽悠了，你也来试试吧",self.loanCal.bloan,self.loanCal.gloan,self.loanCal.deadline,self.results[0]];
            [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeWeb;
            [UMSocialWechatHandler setWXAppId:kWXAppID url:kRong360Host];
            [UMSocialConfig setQQAppId:kTencentID url:kRong360Host importClasses:@[[QQApiInterface class],[TencentOAuth class]]];
            
            [UMSocialSnsService presentSnsIconSheetView:self
                                                 appKey:kUMSocialKey
                                              shareText:shareText
                                             shareImage:[UIImage imageNamed:kShareIcon]
                                        shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToQQ,nil]
                                               delegate:nil];
            break;
        }
        case 4:{
            WebViewController *webVC = [[WebViewController alloc]initWithUrl:GJJDKUrl title:@"公积金贷款办理攻略" desc:GJJDKDesc];
            webVC.type = HTML5ShareUrl;
            [self.navigationController pushViewController:webVC animated:YES];
            break;
        }
        default:
            break;
    }
}

- (void)initSegmentControl{
    
    NSArray *segmentedArray = [[NSArray alloc]initWithObjects:@"等额本息",@"等额本金",nil];
    
    //初始化UISegmentedControl
    
    self.segmentedControl = [[UISegmentedControl alloc]initWithItems:segmentedArray];
    
    self.segmentedControl.frame = CGRectMake(10.0, 10.0, 300.0, 35.0);
    
    self.segmentedControl.selectedSegmentIndex = 0;//设置默认选择项索引
    
    self.segmentedControl.tintColor = RGBCOLOR(0, 172, 238);
    
    //有基本四种样式
    self.segmentedControl.segmentedControlStyle = UISegmentedControlStylePlain;//设置样式
    
    [self.segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];  //添加委托方法
    [self.view addSubview:self.segmentedControl];
}

//具体委托方法实例

-(void)segmentAction:(UISegmentedControl *)Seg{
    NSInteger Index = Seg.selectedSegmentIndex;
    switch (Index) {
        case 0:{
            NSString *test = [[NSUserDefaults standardUserDefaults]objectForKey:@"cmonth_bx"];
            if (test) {
                self.lastResults = [self getLastDataWithType:Loan_bx];
            }
            self.results = self.loanCal.result_bx;
            self.loanStyle = Loan_bx;
            break;
        }
            
        case 1:{
            NSString *test = [[NSUserDefaults standardUserDefaults]objectForKey:@"cmonth_bj"];
            if (test) {
                self.lastResults = [self getLastDataWithType:Loan_bj];
            }
            self.results = self.loanCal.result_bj;
            self.loanStyle = Loan_bj;
            break;
        }
        default:
            break;
    }
    NSString *test = [[NSUserDefaults standardUserDefaults]objectForKey:@"cmonth_bx"];
    if (test) {
        self.lastResults = [self getLastDataWithType:self.loanStyle];
    }
    [self.tableView reloadData];
}
- (void)saveLastData{
    
        [[NSUserDefaults standardUserDefaults]setObject:self.loanCal.result_bj[0] forKey:@"cmonth_bj"];
        [[NSUserDefaults standardUserDefaults]setObject:self.loanCal.result_bj[1] forKey:@"crate_bj"];
        [[NSUserDefaults standardUserDefaults]setObject:self.loanCal.result_bj[2] forKey:@"ctotal_bj"];
        [[NSUserDefaults standardUserDefaults]setObject:self.loanCal.result_bj[3] forKey:@"loan_bj"];
        [[NSUserDefaults standardUserDefaults]setObject:self.loanCal.result_bj[4] forKey:@"deadline"];
        [[NSUserDefaults standardUserDefaults]setObject:self.loanCal.result_bj[5] forKey:@"cmondec_bj"];
    
        [[NSUserDefaults standardUserDefaults]setObject:self.loanCal.result_bx[0] forKey:@"cmonth_bx"];
        [[NSUserDefaults standardUserDefaults]setObject:self.loanCal.result_bx[1] forKey:@"crate_bx"];
        [[NSUserDefaults standardUserDefaults]setObject:self.loanCal.result_bx[2] forKey:@"ctotal_bx"];
        [[NSUserDefaults standardUserDefaults]setObject:self.loanCal.result_bx[3] forKey:@"loan_bx"];
        [[NSUserDefaults standardUserDefaults]setObject:self.loanCal.result_bx[4] forKey:@"deadline"];

}
//保存上次结果


- (NSArray *)getLastDataWithType:(LoanStyle)style{
    
    NSMutableArray *mutArray = [NSMutableArray arrayWithCapacity:5];
    if (style == Loan_bj) {
        [mutArray addObject:[[NSUserDefaults standardUserDefaults]objectForKey:@"cmonth_bj"]];
        [mutArray addObject:[[NSUserDefaults standardUserDefaults]objectForKey:@"crate_bj"]];
        [mutArray addObject:[[NSUserDefaults standardUserDefaults]objectForKey:@"ctotal_bj"]];
        [mutArray addObject:[[NSUserDefaults standardUserDefaults]objectForKey:@"loan_bj"]];
        [mutArray addObject:[[NSUserDefaults standardUserDefaults]objectForKey:@"deadline"]];
        [mutArray addObject:[[NSUserDefaults standardUserDefaults]objectForKey:@"cmondec_bj"] ];
    }else if (style == Loan_bx){
        [mutArray addObject:[[NSUserDefaults standardUserDefaults]objectForKey:@"cmonth_bx"]];
        [mutArray addObject:[[NSUserDefaults standardUserDefaults]objectForKey:@"crate_bx"]];
        [mutArray addObject:[[NSUserDefaults standardUserDefaults]objectForKey:@"ctotal_bx"]];
        [mutArray addObject:[[NSUserDefaults standardUserDefaults]objectForKey:@"loan_bx"]];
        [mutArray addObject:[[NSUserDefaults standardUserDefaults]objectForKey:@"deadline"]];
    }
    return mutArray;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self saveLastData];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return self.titles.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.lastResults) {
        if(self.loanStyle == Loan_bx){
            LoanResultCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            cell.mainLabel.text = self.titles[indexPath.row];
            NSString *value = self.results[indexPath.row];
            cell.subLabel.text = [NSString stringWithFormat:@"%@",[DigitalUtil separatedDigitStringWithStr:value]];
            cell.subLabel.textColor = APPCOLOR;
            cell.unitLabel.text = self.unitTitles[indexPath.row];
            if (indexPath.row == 0 || indexPath.row == 1 || indexPath.row == 2) {
                if (indexPath.row == 0) {
                    cell.subLabel.textColor = [UIColor redColor];
                }
                NSString *lastRes = self.lastResults[indexPath.row];
                cell.lastLabel.text = [NSString stringWithFormat:@"上次结果: %@%@",[DigitalUtil separatedDigitStringWithStr:lastRes],self.unitTitles[indexPath.row]];
            }else{
                cell.lastLabel.text = [NSString stringWithFormat:@"上次输入: %@%@",self.lastResults[indexPath.row],self.unitTitles[indexPath.row]];
            }
            return cell;

        }else if (self.loanStyle == Loan_bj){
            if(indexPath.row == 0){
                LoanResultExtraCell *cell = [tableView dequeueReusableCellWithIdentifier:ExtraCellIdentifier];
                cell.sub1Label.text = self.results[indexPath.row];
                cell.sub2Label.text = self.results[indexPath.row+5];
                NSString *lastRes = self.lastResults[indexPath.row];
                cell.lastLabel.text = [NSString stringWithFormat:@"上次结果: %@%@ 每月递减%@元",[DigitalUtil separatedDigitStringWithStr:lastRes],self.unitTitles[indexPath.row],self.lastResults[indexPath.row+5]];
                return cell;
            }else{
                LoanResultCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
                cell.mainLabel.text = self.titles[indexPath.row];
                NSString *value = self.results[indexPath.row];
                cell.subLabel.text = [NSString stringWithFormat:@"%@",[DigitalUtil separatedDigitStringWithStr:value]];
                if (indexPath.row == 1 || indexPath.row == 2) {
                    NSString *lastRes = self.lastResults[indexPath.row];
                    cell.lastLabel.text = [NSString stringWithFormat:@"上次结果: %@%@",[DigitalUtil separatedDigitStringWithStr:lastRes],self.unitTitles[indexPath.row]];
                }else if (indexPath.row == 3 || indexPath.row == 4){
                    cell.lastLabel.text = [NSString stringWithFormat:@"上次输入: %@%@",self.lastResults[indexPath.row],self.unitTitles[indexPath.row]];
                }
                return cell;
            }
        }
        
    }else{
        if(self.loanStyle == Loan_bx){
            LoanResultCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            cell.mainLabel.text = self.titles[indexPath.row];
            cell.subLabel.text = self.results[indexPath.row];
            cell.subLabel.textColor = [UIColor redColor];
            cell.unitLabel.text = self.unitTitles[indexPath.row];
            return cell;
            //cell.lastLabel.text = [NSString stringWithFormat:@"上次输入:%@%@",self.lastResults[indexPath.row],self.unitTitles[indexPath.row]];
        }else if (self.loanStyle == Loan_bj){
            if(indexPath.row == 0){
                LoanResultExtraCell *cell = [tableView dequeueReusableCellWithIdentifier:ExtraCellIdentifier];
                cell.mainLabel.text = self.titles[indexPath.row];
                cell.sub1Label.text = self.results[indexPath.row];
                cell.sub2Label.text = self.results[indexPath.row+5];
                cell.lastLabel.text = [NSString stringWithFormat:@"上次输入:%@%@ 每月递减%@元",self.lastResults[indexPath.row],self.unitTitles[indexPath.row],self.lastResults[indexPath.row+5]];
                return cell;
            }else{
                LoanResultCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
                cell.mainLabel.text = self.titles[indexPath.row];
                cell.subLabel.text = self.results[indexPath.row];
                cell.unitLabel.text = self.unitTitles[indexPath.row];
                return cell;
               // cell.lastLabel.text = [NSString stringWithFormat:@"上次输入:%@%@",self.lastResults[indexPath.row],self.unitTitles[indexPath.row]];
            }
        }

    }
    
    // Configure the cell...
    return nil;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
